package org.gem.example;

import org.gem.example.product.Fruit;
import org.gem.example.sale.ShoppingCart;
import org.gem.example.sale.ShoppingItem;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Validation {
    public static void validateCalculation(ShoppingCart cart, BigDecimal expectedTotal) {
        BigDecimal actualTotal = cart.getTotalPrice();
        expectedTotal = expectedTotal.setScale(2, RoundingMode.HALF_UP);
        if (actualTotal.subtract(expectedTotal).abs().compareTo(new BigDecimal("0.001")) <= 0) {
            System.out.println("验证通过 - 预期总价: " + expectedTotal + ", 实际总价: " + actualTotal);
        } else {
            System.err.println("验证失败 - 预期总价: " + expectedTotal + ", 实际总价: " + actualTotal);
            printDetailedReceipt(cart);
        }
    }

    private static void printDetailedReceipt(ShoppingCart cart) {
        System.out.println("\n===== 购物明细 =====");
        for (ShoppingItem item : cart.getItems()) {
            Fruit fruit = item.getFruit();
            BigDecimal itemTotal = item.getTotalPrice();
            System.out.printf("%s x %f斤 = %.2f元 (单价: %.2f元/斤)%n",
                    fruit.getName(),
                    item.getQuantity(),
                    itemTotal,
                    fruit.getPrice());
        }
        System.out.println("-------------------");
        System.out.printf("总价: %.2f元%n", cart.getTotalPrice());
    }
}
